import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'layout',
    component: () => import('../views/Layout.vue'),
    //定义嵌套路由
    children:[
      {
        path: '/admin',
        name: '管理员页面内容组件',
        component: () => import('../views/Admin.vue'),
      },
      {
        path: '/role',
        name: '角色页面内容组件',
        component: () => import('../views/Role.vue'),
      },
      {
        path: '/menu',
        name: '菜单页面内容组件',
        component: () => import('../views/Menu.vue'),
      },
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue'),
  }
]

const router = new VueRouter({
  //mode: 'history',
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
});


// 配置路由的导航守卫
router.beforeEach((to, from, next) => {
  // 如果访问登录的路由地址，放过
  if (to.name === 'login') {
    next();
  } else {
    // 如果请求的不是登录页面，验证token
    // 1. 获取本地存储中的token
    const token = localStorage.getItem('base_admin_token');
    if (!token) {
      // 2. 如果没有token，跳转到登录
      next({
        name: 'login'
      });
    } else {
      // 3. 如果有token，继续往下执行
      next();
    }
  }
});

export default router
